package com.jxs.android.weixi;

import java.io.IOException;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.xmlpull.v1.XmlPullParserException;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;

import com.jxs.android.soap.BuWebService;
import com.jxs.android.soap.IWebService;
import com.jxs.android.util.StartHelper;
import com.jxs.android.util.StringUtils;
import com.jxs.android.util.SysUpdateHolder;
import com.jxs.android.util.VersionHolder;
import com.jxs.android.weiget.LockPatternView;
import com.jxs.android.weiget.PopMsg;
import com.jxs.android.weixi.data.UserInfo;
import com.telecom.weixi.R;
import com.telecom.weixi.WeixiApplication;
import com.telecom.weixi.util.CryptUtil;

//@SuppressLint("HandlerLeak")
public class Login extends AbstractActivity {

	private LockPatternView lockPatternView;
	private Context context;
	private ProgressDialog progressDialog;
	private String imsi = "460036520427761";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		context = this;

		super.initTopBar(savedInstanceState, R.layout.bu_login);

		TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		imsi = null == tm.getSubscriberId() ? "" : tm.getSubscriberId();
		if (StringUtils.isEmpety(imsi)) {
			PopMsg.show("请插入SIM卡！");
			finish();
		}
		imsi = "460030309442061";// new
		// imsi = "460036520427761";

		lockPatternView = (LockPatternView) this.findViewById(R.id.lock_pattern);
		lockPatternView.setCheckConfirmListener(new LockPatternView.ICheckConfrim() {

			@Override
			public void onLockPattern(boolean bInit, boolean matched) {
				if (bInit) {
					progressDialog = ProgressDialog.show(context, "", "登录中，请稍候...", true);
					progressDialog.setCancelable(true);
					login(lockPatternView.getPathWord());
					lockPatternView.resetGraphData();
					lockPatternView.resetState();
				}
			}
		}, this);
	}

	private void login(final String password) {
		final CryptUtil crypt = CryptUtil.getInstance();
		new Thread(new Runnable() {

			@Override
			public void run() {
				String wsdl_url = WeixiApplication.WSDL_URL;// wsdl
				String namespace = WeixiApplication.WSDL_NAME_SPACE;// namespace
				String methodName = "login";// 要调用的方法名称
				SoapObject request = new SoapObject(namespace, methodName);
				request.addProperty("password", crypt.encryptAES(password, CryptUtil.getKey()));

				request.addProperty("imsiCode", crypt.encryptAES(imsi, CryptUtil.getKey()));
				request.addProperty("imeiCode", crypt.encryptAES(((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).getDeviceId(), CryptUtil.getKey()));
				request.addProperty("systemVersion", android.os.Build.VERSION.RELEASE);
				request.addProperty("clientVersion", VersionHolder.getVersionName(context));
				request.addProperty("longitude", "105");
				request.addProperty("latitude", "44");
				BuWebService webService = new BuWebService(wsdl_url, request);
				webService.setDoNet(false);
				webService.requestWSDL(new IWebService() {
					@Override
					public void logic(SoapSerializationEnvelope envelope) throws IOException, XmlPullParserException {
						SoapObject response = (SoapObject) envelope.getResponse();
						paserLogin(response, password);
					}
				});
			}
		}).start();
	}

	private void paserLogin(SoapObject soapObject, String password) {
		String stauts = soapObject.getProperty("result").toString();
		if ("-1".equals(stauts)) {
			Message msg = new Message();
			msg.what = UPDATE_VERSION;
			String objs[] = new String[2];
			objs[0] = "版本过期，需要下载新版本!";
			objs[1] = soapObject.getProperty("url").toString();
			msg.obj = objs;
			handler.sendMessage(msg);
		} else if ("2".equals(stauts)) {
			Message msg = new Message();
			msg.what = ERROR_MSG;
			msg.obj = "手势码错误";
			handler.sendMessage(msg);
		} else if ("0".equals(stauts)) {
			Message msg = new Message();
			msg.what = ERROR_MSG;
			msg.obj = "该账号未授权!";
			handler.sendMessage(msg);
		} else if ("1".equals(stauts)) {
			UserInfo userInfo = new UserInfo();
			userInfo.setTicket(soapObject.getProperty("ticket").toString());
			userInfo.setUserId(soapObject.getProperty("userId").toString());
			userInfo.setLatn_id(soapObject.getProperty("latn_id").toString());
			WeixiApplication.setUserInfo(userInfo);
			WeixiApplication.getApplication().setTicket(userInfo.getTicket());
			WeixiApplication.getApplication().setUserId(userInfo.getUserId());
			WeixiApplication.getApplication().setLatnId(userInfo.getLatn_id());
			WeixiApplication.getApplication().setPasswd(password);

			handler.sendEmptyMessage(LOGIN_ON);
		}
	}

	private int LOGIN_ON = 0x110;
	private int UPDATE_VERSION = 0x111;
	private int ERROR_MSG = 0x112;

//	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (null != progressDialog && progressDialog.isShowing()) {
				progressDialog.cancel();
			}
			if (msg.what == LOGIN_ON) {
				StartHelper.startActivity(new Intent(context, MainTabActivity.class));
				finish();
			} else if (msg.what == ERROR_MSG) {
				PopMsg.show((String) msg.obj);
			} else if (msg.what == UPDATE_VERSION) {
				String objs[] = (String[]) msg.obj;
				SysUpdateHolder.showUpdataDialog(Login.this, objs[0], "下载新版本", objs[1], new SysUpdateHolder.UpdateCancelListern() {
					@Override
					public void cancel() {
						finish();
					}
				});
			}
		}

	};

}